package com.handpay.nocardpay.baselibrary.notification.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.model.bean.BaseErrorInfo;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.db.ormlite.DataBaseModel;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.notification.view.activity.NoticeActivity;
import com.handpay.nocardpay.baselibrary.notification.model.bean.NoticeBody;
import com.handpay.nocardpay.baselibrary.notification.model.bean.UserNoticeBean;
import com.handpay.nocardpay.baselibrary.notification.presenter.NoticePresenterImpl;
import com.handpay.nocardpay.baselibrary.notification.push.NoticePushFactory;
import com.handpay.nocardpay.baselibrary.notification.view.INotice;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by fplei on 2017/8/10.<br/>
 * this service is use to query notices data from online.
 */

public class NoticeService extends Service implements INotice {
    public static final String TAG = NoticeService.class.getName();
    private static final int IntervalTime_Alarm = 300 * 1000;
    //        	private static final int IntervalTime_Alarm = 5 * 1000;
    private Binder mBinder = new Binder();
    private Timer mTimer;
    private TimerTask mTimerTask;
    /**
     * Notification管理
     */
    public NotificationManager mNotificationManager;
    private NoticePresenterImpl noticePresenter = null;
    public static final String NOTICE_BEAN = "noticeBody";
    public static final String START_WITH = "from";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }


    public class Binder extends android.os.Binder {
        public NoticeService getService() {
            return NoticeService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HPLog.i(HPLog.LFP_TAG, "NoticeService has onCreate...");
        mTimer = new Timer();
        noticePresenter = new NoticePresenterImpl(this, this.getApplicationContext());
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                doGetNotices();
            }
        };
        mTimer.schedule(mTimerTask, 0, IntervalTime_Alarm);
        initService();
    }

    private void doGetNotices() {
        HPLog.d(HPLog.SSX_TAG, "----------------------------doGetNotices--------------------------------");
        String userId = AccountUtils.getUserId(this.getApplicationContext());
        if (TextUtils.isEmpty(userId))
            return;
        try {
            List<NoticeBody> list = DataBaseModel.getInstance(this).queryNotices(userId);
            if (list == null || list.size() == 0) {
                PreferenceManager.getInstance(this.getApplicationContext()).remove(userId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HPLog.i(HPLog.LFP_TAG, "NoticeService::userId:" + userId);
        String lastUpdateTime = PreferenceManager.getInstance(this.getApplicationContext()).getString(userId, "");
        HashMap<String, Object> params = new HashMap<>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        params.put(BaseProtocolKey.CLIENTCHANNEL, NoCardPayConfig.CLIENTCHANNEL);
        params.put(BaseProtocolKey.UPDATETIME, lastUpdateTime);
        HPLog.i(HPLog.LFP_TAG, "NoticeService::doGetNotices::params :" + params.toString());
        noticePresenter.queryNotices(params, false);
    }

    @Override
    public void showNotices(UserNoticeBean userNoticeBean) {
        String userId = AccountUtils.getUserId(NoticeService.this);
        String lastUpdateTime = userNoticeBean.getLastUpdateTime();
        PreferenceManager.getInstance(NoticeService.this.getApplicationContext()).putString(userId, lastUpdateTime);
        List<NoticeBody> noticeLists = userNoticeBean.getList();
        if (noticeLists != null && noticeLists.size() > 0) {
            for (NoticeBody noticeBody : noticeLists) {
                noticeBody.setUserId(userId);
                noticeBody.setLastUpdateTime(lastUpdateTime);
                noticePresenter.addNotice(noticeBody);
            }
            HPLog.d(HPLog.SSX_TAG, "消息总条数:" + noticeLists.size());
            HPLog.d(HPLog.SSX_TAG, "排序前:" + noticeLists.toString());
            Collections.sort(noticeLists, new Comparator<NoticeBody>() {
                @Override
                public int compare(NoticeBody o1, NoticeBody o2) {//自定义排序规则，时间最大的排序在最前面。
                    try {//NumberFormatException防止服务器返回数据出现问题
                        long l1 = Long.valueOf(o1.getTime());
                        long l2 = Long.valueOf(o2.getTime());
                        if (l1 > l2) {
                            return -1;
                        } else if (l1 < l2) {
                            return 1;
                        } else {
                            return 0;
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        return 0;
                    }
                }
            });
            HPLog.d(HPLog.SSX_TAG, "排序后:" + noticeLists.toString());
//              通知栏消息，只有当服务器返回数据的时候才显示最后一条通知消息。
            NoticeBody lastNotice = noticeLists.get(0);
            if (lastNotice != null) {
                isShowNotice(lastNotice);
            }
        }
        /**
         * 检测数据库是否有未读消息，两种情况
         * 1.服务器没有返回新消息，原有数据库还有未读消息
         * 2.服务器有返回新消息
         */

        checkHasNewNotice(userId);
    }

    //检测是否有新的消息在数据库
    private void checkHasNewNotice(String userId) {
        if (!TextUtils.isEmpty(userId)) {
            boolean hasNew = noticePresenter.isReadNotice(userId);
            HPLog.i(HPLog.LFP_TAG, "checkHasNewNotice hasNew:" + hasNew);
            NoticePushFactory.with().doBroadCastNotice(hasNew);
        }
    }

    @Override
    public void showErrorAlert(BaseErrorInfo baseErrorInfo) {
        HPLog.e(HPLog.LFP_TAG, "noticeService error:" + baseErrorInfo.toString());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_REDELIVER_INTENT;
    }

    @Override
    public void onDestroy() {
        HPLog.d(HPLog.SSX_TAG, "----------------onDestroy------------------");
        super.onDestroy();
        if (mTimerTask != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        clearAllNotify();
        noticePresenter.onDestory();
        mNotificationManager = null;
    }

    /**
     * 通知栏显示最新的一条通知
     *
     * @param info 需要显示的通知
     */
    public void isShowNotice(NoticeBody info) {
        mNotificationManager.cancel(100);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
//		//PendingIntent 跳转动作
        Intent intent = new Intent(this, NoticeActivity.class);
        intent.putExtra(NoticeActivity.OPEN_TYPE, 1);
        intent.putExtra(START_WITH, this.getClass().getSimpleName());
        intent.putExtra(NoticeService.NOTICE_BEAN, info);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker("有最新通知").setContentTitle(info.getTitle()).setContentText(CommonUtils.StringFilter(info.getContent())).setContentIntent(pendingIntent);
        Notification mNotification = mBuilder.build();
        //设置通知  消息  图标
//        mNotification.icon = R.drawable.ic_launcher;
        //在通知栏上点击此通知后自动清除此通知
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;//FLAG_ONGOING_EVENT 在顶部常驻，可以调用下面的清除方法去除  FLAG_AUTO_CANCEL  点击和清理可以去调
        //设置显示通知时的默认的发声、震动、Light效果
        mNotification.defaults = Notification.DEFAULT_VIBRATE;
        //设置发出消息的内容
        mNotification.tickerText = "有最新通知";
        //设置发出通知的时间
        mNotification.when = System.currentTimeMillis();
        mNotification.flags = Notification.FLAG_AUTO_CANCEL; //在通知栏上点击此通知后自动清除此通知
        mNotificationManager.notify(100, mNotification);
    }

    /**
     * 初始化要用到的系统服务
     */
    private void initService() {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    /**
     * 清除所有通知栏
     */
    public void clearAllNotify() {
        mNotificationManager.cancelAll();// 删除你发的所有通知
    }


}
